function [Age] = FieldAge(DS)
% Compute field age.

% % Unstack dataset to have state-years in columns:
% dsWide = unstack(DS(:,{'FID_Grid','StateCode','Year'}),'StateCode','Year');
% %dsWide = unstack(DS,'StateCode','Year');
% NewVarNames = {'x2003','x2004','x2005','x2006','x2007','x2008','x2009','x2010','x2011','x2012','x2013'};

% For Field Age we adopt the convention: 
% em_reforma fields are age 1,
% reformada and expansao are age 2, and so on. 
% Non-sugarcane fields are age 0. Unknown age fields are age NaN.

% Ages for SP and CS CanasatDataset must be computed separately


% First do SP:
AgeSP = zeros(sum(DS.CanasatDataset == 1),11); % Eleven years in the sample
StatesSP = double(DS(DS.CanasatDataset == 1,3:13));


% If initially the state is:
AgeSP(StatesSP(:,1) == 1 | StatesSP(:,1) == 4,1) = 2; % New expansion or reformada, set age = 2. 
AgeSP(StatesSP(:,1) == 2,1) = 1;                    % em_reforma, set age = 1.
AgeSP(StatesSP(:,1) == 3,1) = NaN;                  % Soca, set age = NaN. (unkown age) 
AgeSP(StatesSP(:,2) == 1,1) = 1;                    % If next period state is expansion, age = 1.
AgeSP(StatesSP(:,2) == 4,1) = 1;                    % If classified as reformed in future period, then it must have been reforming in the previous period.
                                         % This affects a small portion of fields with inconsistent classification.
for i=2:11
    AgeSP(StatesSP(:,i) == 3 & AgeSP(:,i-1) > 0,i)      = AgeSP(StatesSP(:,i) == 3 & AgeSP(:,i-1) > 0,i-1) + 1; % Update age of old fields.
    AgeSP(StatesSP(:,i) == 3 & isnan(AgeSP(:,i-1)),i)   = NaN; % If age still unknown...
    AgeSP(StatesSP(:,i) == 1 | StatesSP(:,i) == 4,i)    = 2; % New Expansion, age = 2
    if i~= 11
        AgeSP(StatesSP(:,i+1) == 1,i) = 1;
        AgeSP(StatesSP(:,i) == 2 & StatesSP(:,i+1)~=0,i)    = 1; % em_reforma, age = 1. If it was soca and transitions to 0 then it also undergoes 
                                                           % em_reforma before it enters 0 
        AgeSP( StatesSP(:,i+1) == 4 ,i) = 1; % If classified as reformed in future period, then it must have been reforming in the previous period.
                                         % This affects a small portion of fields with inconsistent classification.
    end    
end

% Now do CS:
AgeCS = zeros(sum(DS.CanasatDataset == 2),11); % Eleven years in the sample
StatesCS = double(DS(DS.CanasatDataset == 2,3:13));

% The first year (2003) for CS dataset will be NaN because there is no data
% available for other periods.

% All already established sugarcane areas received state =5 in canasat
% data.
% If initially the state is:
AgeCS(:,1) = NaN; % 2003 state unknown for all fields in CS
AgeCS(StatesCS(:,2) == 1 | StatesCS(:,2) == 4,2) = 2; % New expansion or reformada, set age = 2. 
AgeCS(StatesCS(:,2) == 2,2) = 1;                    % em_reforma, set age = 1.
AgeCS(StatesCS(:,2) == 5,2) = NaN;                  % Soca, set age = NaN. (unkown age) 
AgeCS(StatesCS(:,3) == 1,2) = 1;                    % If next period state is expansion, age = 1.
AgeCS(StatesCS(:,2) == 4,2) = 1;                    % If classified as reformed in future period, then it must have been reforming in the previous period.
                                         % This affects a small portion of fields with inconsistent classification.

for i=3:11
    AgeCS(StatesCS(:,i) == 3 & AgeCS(:,i-1) > 0,i)      = AgeCS(StatesCS(:,i) == 3 & AgeCS(:,i-1) > 0,i-1) + 1; % Update age of old fields.
    AgeCS(StatesCS(:,i) == 3 & isnan(AgeCS(:,i-1)),i)   = NaN; % If age still unknown...
    AgeCS(StatesCS(:,i) == 1 | StatesCS(:,i) == 4,i)    = 2; % New Expansion, age = 2
    if i~= 11
        AgeCS(StatesCS(:,i+1) == 1,i) = 1;
        AgeCS(StatesCS(:,i) == 2 & StatesCS(:,i+1)~=0,i)    = 1; % em_reforma, age = 1. If it was soca and transitions to 0 then it also undergoes 
                                                           % em_reforma before it enters 0 
        AgeCS( StatesCS(:,i+1) == 4 ,i) = 1; % If classified as reformed in future period, then it must have been reforming in the previous period.
                                         % This affects a small portion of fields with inconsistent classification.
    end    
end

Age = zeros(size(DS,1),11);
Age(DS.CanasatDataset == 1,:) = AgeSP;
Age(DS.CanasatDataset == 2,:) = AgeCS;

Age(DS.S2013 == 2 & DS.S2012 == 3,11)    = NaN; % For the last period, if you go in em_reforma, 
                                                % we don't know what's the outcome in the next period, 
                                                % so we say the age is unknown

                                                

% Store age                                                          
% DS.Age = Age;
% DS_Aged = DS;

                                                                                                          
% % Create a wide dataset with Age spread in columns and FID_Grid id:                                                                                                          
% Name      = ['FID_Grid' NewVarNames];
% dsWideAge = mat2dataset([dsWide.FID_Grid AgeSP],'VarNames',Name);
% 
% % Now stack this dataset:
% dsTallAge = stack(dsWideAge,NewVarNames,'newDataVarName','Age'); 
% 
% % Now this is a little messy: we want to have a variable in this tall
% % dataset that corresponds to the year variable. The problem is that the
% % correponding Age_Indicator in the dsTallAge above has an x in front of
% % the year. We will now remove this x...
% 
% K = dsTallAge.Age_Indicator; % Get string of cells
% K = char(K); % Transfor into character array so we can remove the x.
% K = K(:,[2:end]); % Remove the x.
% K = cellstr(K); % Convert back to cell.
% dsTallAge.Year = str2double(K); % Convert to double.
% 
% 
% DS_Expanded = join(DS,dsTallAge(:,{'FID_Grid','Year','Age'}));
% %DS_Expanded.geocodigo = str2double(DS_Expanded.geocodigo);
% %DS_WideAge  = unstack(DS_Expanded(:,{'FID_Grid', 'Year', 'Age'}),'Age','Year');


